﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using SPFluid.Core.Exceptions;

namespace SPFluid.Core.Utilities
{
    public static partial class Map
    {
        private const string StringSeparator = ";#";

        public static TCollection CollectionFromDatabase<T, TCollection>(object value)
            where TCollection : ICollection<T>, new()
        {
            if (value == null)
            {
                return new TCollection();
            }

            var type = typeof(T);
            try
            {
                var stringValue = Convert.ToString(value);

                if (type == typeof(string))
                {
                    var result = stringValue.Split(new[] { StringSeparator }, StringSplitOptions.RemoveEmptyEntries);
                    var collection = new TCollection();
                    foreach (var item in result)
                    {
                        collection.Add((T)(object)item);
                    }

                    return collection;
                }

                if (type == typeof(SPFieldLookupValue))
                {
                    var fieldLookupValueCollection = new SPFieldLookupValueCollection(stringValue);
                    
                    var collection = new TCollection();
                    foreach (var fieldLookupValue in fieldLookupValueCollection)
                    {
                        collection.Add((T)(object)fieldLookupValue);
                    }

                    return collection;
                }
            }
            catch (Exception e)
            {
                throw new MappingException();
            }

            throw new MappingException();
        }

        public static object CollectionToDatabase<T, TCollection>(TCollection collection)
            where TCollection : IEnumerable<T>
        {
            if (!collection.Any())
            {
                return null;
            }

            var type = typeof(T);

            if (type == typeof(string))
            {
                return string.Format(";#{0};#", string.Join(";#", collection.Cast<string>().ToArray()));
            }

            if (type == typeof(SPFieldLookupValue))
            {
                var fieldLookupValueCollection = new SPFieldLookupValueCollection();
                fieldLookupValueCollection.AddRange(collection.Cast<SPFieldLookupValue>());
                return fieldLookupValueCollection;
            }

            return collection;
        }
    }
}